package com.ycz.algorithm.utils.stack;

import java.util.ArrayList;

/**
 * @Description 基于数组实现的栈
 * @ClassName ArrayStack
 * @Author yanchengzhi
 * @date 2024.11.20 23:50
 */
public class ArrayStack {

    private ArrayList<Integer> stack;

    public ArrayStack() {
        // 栈初始化
        stack = new ArrayList<>();
    }

    // 获取栈深度
    public int size() {
        return stack.size();
    }

    // 判断栈空
    public boolean isEmpty() {
        return size() == 0;
    }

    // 入栈
    public void push(int num) {
        stack.add(num);
    }

    // 出栈
    public int pop() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("栈空无法出栈！");
        }
        return stack.remove(size() - 1);
    }

    // 访问栈顶元素
    public int peek() {
        if (isEmpty()) {
            throw new IndexOutOfBoundsException("栈空无法出栈！");
        }
        return stack.get(size() - 1);
    }

    // 转为数组
    public Object[] toArray() {
        return stack.toArray();
    }

    public static void main(String[] args) {
        // 初始化栈
        ArrayStack arrayStack = new ArrayStack();
        // 入栈
        arrayStack.push(1);
        arrayStack.push(2);
        arrayStack.push(3);
        commonPrint(arrayStack.toArray());
        System.out.println("栈顶元素：" + arrayStack.peek());
        System.out.println("栈深度：" + arrayStack.size());
        // 出栈
        int num = arrayStack.pop();
        System.out.println("出栈元素：" + num);
        System.out.println("栈深度：" + arrayStack.size());
        commonPrint(arrayStack.toArray());
    }

    private static void commonPrint(Object[] res) {
        for (Object obj : res) {
            int num = (int) obj;
            System.out.print(num + "\t");
        }
        System.out.println();
    }

}
